from django.conf import settings
from django.db import models
from django.urls import reverse

from common.models import Common, CommonAuto
from shop.models import ShopInfo


class ProductType(CommonAuto):
    """商品类别"""
    shop = models.ForeignKey(ShopInfo, verbose_name=u'店铺', on_delete=models.CASCADE, related_name='product_type_shop')
    name = models.CharField(u'名称', max_length=100, default='')
    alias = models.CharField(u'别名', max_length=100, default='', blank=True)
    priority = models.IntegerField(u'显示优先级', default=0, blank=True)

    class Meta:
        db_table = 'product_type'
        verbose_name = '商品类别'
        ordering = ['-priority', '-create_time']


class Product(Common):
    """商品"""
    shop = models.ForeignKey(ShopInfo, verbose_name=u'店铺', on_delete=models.CASCADE, default='', blank=True,
                             related_name='product_shop')
    type = models.ForeignKey(ProductType, verbose_name=u'商品类别', default='', blank=True, null=True,
                             on_delete=models.CASCADE, related_name='product_type')
    title = models.CharField(u'商品名称', max_length=255, default='')
    specs = models.CharField(u'规格', max_length=100, default='')
    image = models.CharField(u'图片', max_length=1024, default='')
    # video = models.ForeignKey(VideoInfo, verbose_name=u'视频', null=True, on_delete=models.SET_NULL, blank=True)
    images = models.CharField(u'图片组', max_length=1024, default='', blank=True)

    price_original = models.IntegerField(u'原价(分)', default=0, blank=True)
    price_discount = models.IntegerField(u'折扣价(分)', default=0, blank=True)

    inventory = models.IntegerField(u'库存', default=-1, blank=True, help_text=u'库存数量，-1为库存无限')
    desc = models.TextField(u'介绍', default='')

    shelve = models.BooleanField(u'上架', default=False, help_text=u'False为下架，True为上架')
    priority = models.IntegerField(u'优先级', default=0, blank=True)

    LEVEL_NORMAL, LEVEL_MASTER = 1, 2
    LEVEL_TYPE = ((LEVEL_NORMAL, u'不推荐'), (LEVEL_MASTER, u'推荐'))
    level = models.IntegerField(u'产品级别', choices=LEVEL_TYPE, default=LEVEL_NORMAL, blank=True)

    def get_image_url(self):
        return settings.QINIU_DOMAIN + self.image

    def get_mobile_url(self):
        return 'http://qxb.dongpouu.com%s?shop=%s' % (reverse('product:detail', args=[self.id]), self.shop_id)

    def get_buy_url(self):
        return '%s?shop=%s' % (reverse('order:product_create_api'), self.shop_id)

    def get_pay_url(self):
        return '%s?shop=%s' % (reverse('order:pay_product'), self.shop_id)

    class Meta:
        db_table = 'product_info'
        verbose_name = '商品信息'
        ordering = ['-priority', '-create_time']
